<template>
  <el-dialog
      :visible="true"
      width="800px"
      top="10vh"
      :close-on-click-modal="false"
      :show-close="true"
      custom-class="chat-panel-dialog"
      @close="$emit('close')"
  >
    <div class="chat-panel">
      <!-- 左侧会话列表 -->
      <div class="chat-sidebar">
        <el-tabs v-model="activeTab" tab-position="top" stretch>
          <el-tab-pane label="联系人" name="contacts">
            <el-menu
                :default-active="activeSessionId"
                class="chat-menu"
                @select="handleSessionSelect"
            >
              <el-menu-item
                  v-for="contact in contacts"
                  :key="'contact-' + contact.id"
                  :index="'contact-' + contact.id"
              >
                <i class="el-icon-user"></i>
                <span>{{ contact.name }}</span>
                <el-badge
                    v-if="unreadMap['contact-' + contact.id]"
                    :value="unreadMap['contact-' + contact.id]"
                    class="unread-badge"
                    type="danger"
                />
              </el-menu-item>
            </el-menu>
          </el-tab-pane>
          <el-tab-pane label="群聊" name="groups">
            <el-menu
                :default-active="activeSessionId"
                class="chat-menu"
                @select="handleSessionSelect"
            >
              <el-menu-item
                  v-for="group in groups"
                  :key="'group-' + group.id"
                  :index="'group-' + group.id"
              >
                <i class="el-icon-chat-dot-square"></i>
                <span>{{ group.name }}</span>
                <el-badge
                    v-if="unreadMap['group-' + group.id]"
                    :value="unreadMap['group-' + group.id]"
                    class="unread-badge"
                    type="danger"
                />
              </el-menu-item>
            </el-menu>
          </el-tab-pane>
          <el-tab-pane label="系统消息" name="notices">
            <el-menu
                :default-active="activeSessionId"
                class="chat-menu"
                @select="handleSessionSelect"
            >
              <el-menu-item
                  v-for="notice in notices"
                  :key="'notice-' + notice.id"
                  :index="'notice-' + notice.id"
              >
                <i class="el-icon-bell"></i>
                <span>{{ notice.title }}</span>
                <el-badge
                    v-if="unreadMap['notice-' + notice.id]"
                    :value="unreadMap['notice-' + notice.id]"
                    class="unread-badge"
                    type="danger"
                />
              </el-menu-item>
            </el-menu>
          </el-tab-pane>
        </el-tabs>
      </div>
      <!-- 右侧聊天窗口 -->
      <div class="chat-main">
        <div class="chat-header">
          <span v-if="currentSessionType === 'contact'">
            与 <b>{{ currentSession.name }}</b> 聊天
          </span>
          <span v-else-if="currentSessionType === 'group'">
            群聊：<b>{{ currentSession.name }}</b>
          </span>
          <span v-else-if="currentSessionType === 'notice'">
            系统消息：<b>{{ currentSession.title }}</b>
          </span>
        </div>
        <div class="chat-messages" ref="messages">
          <div
              v-for="msg in currentMessages"
              :key="msg.id"
              :class="['chat-message', msg.fromSelf ? 'self' : 'other']"
              @contextmenu.prevent="msg.fromSelf && !msg.recalled && showRecallMenu(msg)"
          >
            <div class="msg-user" v-if="currentSessionType !== 'contact'">
              {{ msg.user }}
            </div>
            <div v-if="msg.recalled" class="recalled-msg">
              {{ msg.fromSelf ? '你撤回了一条消息' : `${msg.user}撤回了一条消息` }}
            </div>
            <div v-else>
              <div v-if="msg.type === 'image'">
                <img :src="msg.content" style="max-width:120px;max-height:120px;"/>
              </div>
              <div v-else>
                {{ msg.content }}
              </div>
            </div>
            <div class="msg-time">
              {{ msg.time }}
              <span v-if="msg.fromSelf && !msg.recalled" class="read-status">
                {{ msg.read ? '已读' : '未读' }}
              </span>
              <el-button
                  v-if="msg.fromSelf && !msg.recalled"
                  type="text"
                  size="mini"
                  @click="recallMessage(msg)"
                  style="margin-left:8px;"
              >撤回
              </el-button>
            </div>
          </div>
        </div>
        <div v-if="currentSessionType !== 'notice'" class="chat-input">
          <!-- 表情 -->
          <el-popover
              placement="top"
              width="300"
              trigger="click"
              v-model="emojiVisible"
          >
            <div class="emoji-panel">
              <span
                  v-for="emoji in emojiList"
                  :key="emoji"
                  class="emoji"
                  @click="insertEmoji(emoji)"
              >{{ emoji }}</span>
            </div>
            <el-button slot="reference" icon="el-icon-smile" size="mini"></el-button>
          </el-popover>
          <!-- 图片上传（模拟） -->
          <el-upload
              class="upload-btn"
              :show-file-list="false"
              :before-upload="beforeUpload"
              :on-change="handleUploadChange"
              action="#"
          >
            <el-button icon="el-icon-picture" size="mini"></el-button>
          </el-upload>
          <!-- 输入框 -->
          <el-input
              type="textarea"
              v-model="inputMessage"
              :rows="2"
              placeholder="请输入消息..."
              @keyup.enter.native="sendMessage"
              style="flex:1;margin:0 10px;"
          />
          <el-button type="primary" @click="sendMessage">发送</el-button>
        </div>
        <div v-else class="chat-input" style="text-align:center;color:#999;">
          系统消息不可回复
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: "ChatPanel",
  data() {
    return {
      activeTab: "contacts",
      contacts: [
        {id: 1, name: "张三"},
        {id: 2, name: "李四"}
      ],
      groups: [
        {id: 1, name: "研发群"},
        {id: 2, name: "管理群"}
      ],
      notices: [
        {id: 1, title: "系统维护通知"},
        {id: 2, title: "审批提醒"}
      ],
      messages: {
        "contact-1": [
          {id: 1, user: "张三", content: "你好！", time: "09:00", fromSelf: false, type: "text", read: true},
          {id: 2, user: "我", content: "你好，有什么事？", time: "09:01", fromSelf: true, type: "text", read: false}
        ],
        "group-1": [
          {id: 1, user: "王五", content: "大家早上好", time: "08:50", fromSelf: false, type: "text", read: true}
        ],
        "notice-1": [
          {id: 1, user: "系统", content: "今晚10点系统维护", time: "08:00", fromSelf: false, type: "text", read: true}
        ]
      },
      unreadMap: {
        "contact-1": 1,
        "group-1": 1,
        "notice-1": 0
      },
      activeSessionId: "contact-1",
      inputMessage: "",
      emojiVisible: false,
      emojiList: ['😀', '😂', '😍', '😢', '👍', '🎉', '😎', '🤔', '😭', '😡', '😱', '🥰']
    };
  },
  computed: {
    currentSessionType() {
      if (!this.activeSessionId) return null;
      if (this.activeSessionId.startsWith("contact-")) return "contact";
      if (this.activeSessionId.startsWith("group-")) return "group";
      if (this.activeSessionId.startsWith("notice-")) return "notice";
      return null;
    },
    currentSession() {
      if (!this.activeSessionId) return {};
      if (this.currentSessionType === "contact") {
        return this.contacts.find(c => "contact-" + c.id === this.activeSessionId) || {};
      }
      if (this.currentSessionType === "group") {
        return this.groups.find(g => "group-" + g.id === this.activeSessionId) || {};
      }
      if (this.currentSessionType === "notice") {
        return this.notices.find(n => "notice-" + n.id === this.activeSessionId) || {};
      }
      return {};
    },
    currentMessages() {
      return this.messages[this.activeSessionId] || [];
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      }
    },
    currentMessages() {
      this.$nextTick(() => {
        this.scrollToBottom();
      });
    }
  },
  methods: {
    handleSessionSelect(index) {
      this.activeSessionId = index;
      this.inputMessage = "";
      // 清除未读
      this.$set(this.unreadMap, index, 0);
      // 模拟已读回执
      (this.messages[index] || []).forEach(msg => {
        if (!msg.fromSelf) msg.read = true;
      });
    },
    sendMessage(content = null, type = "text") {
      const msgContent = content !== null ? content : this.inputMessage.trim();
      if (!msgContent) return;
      const msg = {
        id: Date.now(),
        user: "我",
        content: msgContent,
        time: new Date().toLocaleTimeString().slice(0, 5),
        fromSelf: true,
        type,
        read: false,
        recalled: false
      };
      if (!this.messages[this.activeSessionId]) {
        this.$set(this.messages, this.activeSessionId, []);
      }
      this.messages[this.activeSessionId].push(msg);
      this.inputMessage = "";
      this.scrollToBottom();
      // 模拟对方已读
      setTimeout(() => {
        msg.read = true;
      }, 1000);
    },
    handleClose() {
      this.$bus.$emit("close");
    },
    scrollToBottom() {
      this.$refs.messages && (this.$refs.messages.scrollTop = this.$refs.messages.scrollHeight);
    },
    insertEmoji(emoji) {
      this.inputMessage += emoji;
      this.emojiVisible = false;
    },
    beforeUpload(file) {
      // 这里只做图片类型校验
      const isImage = file.type.startsWith("image/");
      if (!isImage) {
        this.$message.error("只能发送图片文件");
      }
      return isImage;
    },
    handleUploadChange(file) {
      // 模拟图片上传，直接用本地预览
      const reader = new FileReader();
      reader.onload = e => {
        this.sendMessage(e.target.result, "image");
      };
      reader.readAsDataURL(file.raw);
    },
    showRecallMenu(msg) {
      // 右键菜单可扩展，这里直接用按钮
    },
    recallMessage(msg) {
      this.$set(msg, "recalled", true);
    }
  }
};
</script>

<style scoped>
.chat-panel-dialog ::v-deep .el-dialog__body {
  padding: 0;
}

.chat-panel {
  display: flex;
  height: 500px;
}

.chat-sidebar {
  width: 220px;
  border-right: 1px solid #eee;
  background: #fafbfc;
  overflow-y: auto;
}

.chat-menu {
  border: none;
}

.unread-badge {
  float: right;
  margin-left: 8px;
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.chat-header {
  padding: 16px;
  border-bottom: 1px solid #eee;
  font-weight: bold;
  background: #f5f7fa;
}

.chat-messages {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  background: #fff;
}

.chat-message {
  margin-bottom: 12px;
  display: flex;
  flex-direction: column;
  max-width: 70%;
}

.chat-message.self {
  align-self: flex-end;
  background: #e6f7ff;
  border-radius: 8px 8px 0 8px;
  padding: 8px 12px;
}

.chat-message.other {
  align-self: flex-start;
  background: #f4f4f5;
  border-radius: 8px 8px 8px 0;
  padding: 8px 12px;
}

.msg-user {
  font-size: 12px;
  color: #888;
}

.msg-content {
  font-size: 14px;
  margin: 4px 0;
}

.msg-time {
  font-size: 11px;
  color: #bbb;
  text-align: right;
}

.read-status {
  margin-left: 8px;
  color: #67c23a;
}

.recalled-msg {
  color: #aaa;
  font-style: italic;
  font-size: 13px;
  margin: 4px 0;
}

.chat-input {
  padding: 12px 16px;
  border-top: 1px solid #eee;
  background: #fafbfc;
  display: flex;
  align-items: flex-end;
}

.emoji-panel {
  display: flex;
  flex-wrap: wrap;
  max-width: 280px;
}

.emoji {
  font-size: 22px;
  margin: 4px;
  cursor: pointer;
  transition: transform 0.1s;
}

.emoji:hover {
  transform: scale(1.2);
}

.upload-btn {
  margin-right: 8px;
}
</style>
